// import { LoggerService } from '@nestjs/common';
import {
    ArgumentsHost,
    Catch,
    ExceptionFilter,
    HttpException,
    HttpStatus
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Log } from "@/modules/log/entities/log.entity";
import { Repository } from "typeorm";
import { argumentsToString } from "@/common/utils/common";

// import requestIp from "request-ip";

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
    constructor(
        @InjectRepository(Log)
        private readonly logRepository: Repository<Log>
    ) {
    }
    
    async catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp(); // 获取请求上下文
        const request = ctx.getRequest(); // 获取请求上下文中的request对象
        const response = ctx.getResponse(); // 获取请求上下文中的response对
        const status = exception.getStatus();
        const exceptionResponse: any = exception.getResponse();
        // console.log("request",request.user)
        // 设置错误信息
        const message = exception.message
            ? exception.message
            : `${status >= 500 ? "服务器错误（Service Error）" : "客户端错误（Client Error）"}`;
        this.logRepository.save({
            // ip: requestIp.getClientIp(request),
            ip: request.ip,
            userFlag: request?.user?.username || request.headers?.code,
            name: "请求错误",
            method: request.method,
            message:(exceptionResponse?.message || message).toString(),
            arguments: argumentsToString(request), // (request.body || request.params || request.query),
            status,
            path: request.originalUrl,
            type: 0
        });
        console.log("走了http-exception.filter。ts");
        response
            .status(status)
            .json({
                code: status,
                msg: exceptionResponse?.message || message,
                error: exceptionResponse.error,
            });
        // throw new Error('Method not implemented.');
    }
}
